<template>
  <div class="document-container">
    <el-container class="document-layout">
      <el-aside width="70%" class="editor-container">
        <div class="editor-header">
          <el-select v-model="documentType" placeholder="请选择公文类型" style="width: 200px">
            <el-option label="通知" value="notice" />
            <el-option label="报告" value="report" />
            <el-option label="请示" value="request" />
            <el-option label="批复" value="reply" />
          </el-select>
          <div class="editor-tools">
            <el-button type="primary" @click="handleGenerate">AI生成</el-button>
            <el-button type="success" @click="handleStreamGenerate">流式生成</el-button>
            <el-button type="warning" @click="handleSave">保存</el-button>
          </div>
        </div>
        <div class="editor-content">
          <el-input v-model="documentTitle" placeholder="请输入公文标题" class="title-input" />
          <div class="rich-editor">
            <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <div class="editor-warpper">
              <Editor v-model="documentContent" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated"
                @onChange="handleChange" />
            </div>
          </div>
        </div>
      </el-aside>
      <el-main class="ai-container">
        <div class="ai-header">
          <h3>AI 助手</h3>
        </div>
        <div class="ai-messages">
          <div v-for="(message, index) in messages" :key="index" class="message" :class="message.type">
            <div class="message-content">{{ message.content }}</div>
          </div>
        </div>
        <div class="ai-input">
          <el-input v-model="userInput" type="textarea" :rows="3" placeholder="请输入您的问题或需求" />
          <el-button type="primary" @click="handleSend" class="send-button">发送</el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, shallowRef, onBeforeUnmount, onMounted } from "vue";
import { ElMessage } from "element-plus";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { generateAI, streamAI } from '@/apis/model';
import { fetchSSE } from "@/utils/fetch";

// 添加类型声明
interface SSEData {
  content: string;
}

export default defineComponent({
  name: "DocumentEditor",
  components: {
    Editor,
    Toolbar
  },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    let myContent = '';
    // 内容 HTML
    const documentType = ref("");
    const documentTitle = ref("");
    const documentContent = ref("");
    const userInput = ref("");
    const messages = ref([
      {
        type: "ai",
        content: "您好！我是公文写作助手，请问有什么可以帮您？"
      }
    ]);

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      documentContent.value = '';
    });

    const toolbarConfig = {
      excludeKeys: [
        'uploadImage',
        'uploadVideo',
        'insertTable',
        'group-video',
        'group-image',
        'group-code'
      ]
    };

    const editorConfig = {
      placeholder: '请输入公文内容...',
      MENU_CONF: {}
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor: any) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const handleChange = (editor: any) => {
      documentContent.value = editor.getHtml();
    };

    const handleGenerate = async () => {
      if (!documentType.value) {
        ElMessage.warning("请先选择公文类型");
        return;
      }
      if (!documentTitle.value) {
        ElMessage.warning("请输入公文标题");
        return;
      }

      try {
        // 清空编辑器内容
        const editor = editorRef.value;
        if (editor) {
          editor.setHtml('');
        }

        // 调用生成接口
        const response = await generateAI({
          mark: 'myDeepseek',
          message: documentTitle.value
        });

        // 更新编辑器内容
        if (editor && response.data) {
          editor.setHtml(response.data);
        }
      } catch (error) {
        ElMessage.error('生成失败，请重试');
        console.error('生成错误:', error);
      }
    };

    const handleStreamGenerate = () => {
      if (!documentType.value) {
        ElMessage.warning("请先选择公文类型");
        return;
      }
      if (!documentTitle.value) {
        ElMessage.warning("请输入公文标题");
        return;
      }

      // 清空编辑器内容
      const editor = editorRef.value;
      if (editor) {
        editor.setHtml('');
      }
      const abortController = new AbortController();
      fetchSSE(`/api/government/ai/stream?mark=myDeepseek&message=${documentTitle.value}`, {
        method: 'post',
        signal: abortController.signal,
        onAbort: async (text) => {
          console.log("onAbort", text)
        },
        onMessageHandle: async (chunk) => {
          console.log("onMessageHandle", chunk)
        }
      })
      // 调用流式生成接口
      // streamAI(
      //   {
      //     mark: 'myDeepseek',
      //     message: documentTitle.value
      //   },
      //   (data: SSEData, isEnd: boolean) => {
      //     console.log(data, isEnd);
      //     // 如果是第一次接收数据，myContent可能未定义，需要初始化
      //     if (!myContent) {
      //       myContent = '';
      //     }

      //     if (editor && data) {
      //       // 追加新内容到临时变量 
      //       myContent += (data || '');
      //       // 使用累积的内容更新编辑器
      //       editor.setHtml(myContent);
      //     }

      //     if (isEnd) {
      //       // 重置临时变量
      //       myContent = '';
      //       ElMessage.success('生成完成');
      //     }
      //   }
      // );
    };

    const handleSave = () => {
      if (!documentContent.value) {
        ElMessage.warning("请先输入公文内容");
        return;
      }
      // TODO: 保存公文
    };

    const handleSend = () => {
      if (!userInput.value.trim()) {
        return;
      }
      messages.value.push({
        type: "user",
        content: userInput.value
      });
      // TODO: 调用AI接口
      userInput.value = "";
    };

    return {
      documentType,
      documentTitle,
      documentContent,
      userInput,
      messages,
      editorRef,
      mode: 'default',
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleGenerate,
      handleStreamGenerate,
      handleSave,
      handleSend
    };
  }
});
</script>

<style lang="scss" scoped>
.document-container {
  height: 100%;
  width: 100%;

  .document-layout {
    height: 100%;
    width: 100%;
  }

  .editor-container {
    height: 100%;
    padding: 20px;
    background-color: #fff;
    border-right: 1px solid #dcdfe6;

    .editor-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .editor-tools {
        display: flex;
        gap: 10px;
      }
    }

    .editor-content {
      height: calc(100% - 60px);
      display: flex;
      flex-direction: column;

      .title-input {
        margin-bottom: 20px;
      }

      .rich-editor {
        flex: 1;
        overflow: hidden;
        border: 1px solid #ccc;
        z-index: 100;
        display: flex;
        flex-direction: column;
      }

      .editor-warpper {
        flex: 1;
        overflow: hidden;
      }
    }
  }

  .ai-container {
    height: 100%;
    padding: 20px;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;

    .ai-header {
      margin-bottom: 20px;
    }

    .ai-messages {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;

      .message {
        margin-bottom: 15px;

        &.user {
          text-align: right;

          .message-content {
            background-color: #409eff;
            color: white;
            padding: 10px 15px;
            border-radius: 4px;
            display: inline-block;
            max-width: 80%;
          }
        }

        &.ai {
          text-align: left;

          .message-content {
            background-color: #fff;
            padding: 10px 15px;
            border-radius: 4px;
            display: inline-block;
            max-width: 80%;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          }
        }
      }
    }

    .ai-input {
      .send-button {
        margin-top: 10px;
        width: 100%;
      }
    }
  }
}
</style>